package com.questetra.OAuth.apps.Twitter
{
	import com.adobe.serialization.json.JSON;
	import com.questetra.OAuth.apps.Twitter.parser.TwitterStatus;
	import com.questetra.OAuth.core.OAuthEvent;
	import com.questetra.OAuth.core.OAuthManager;
	import com.questetra.OAuth.core.QueryString;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	[Event(name="xml_parce_error", type="com.questetra.OAuth.Twitter.TwitterEvent")]
	[Event(name="status_update", type="com.questetra.OAuth.Twitter.TwitterEvent")]
	[Event(name="on_home_timeline", type="com.questetra.OAuth.Twitter.TwitterEvent")]
	[Event(name="on_mentions", type="com.questetra.OAuth.Twitter.TwitterEvent")]
	[Event(name="on_search", type="com.questetra.OAuth.Twitter.TwitterEvent")]
	public class OAuthTwitter extends OAuthManager
	{
		
		public var use_parser:Boolean = true;
		private var _screen_name:String;
		private var _user_id:String;
		
		public function OAuthTwitter(){
			super();
			trace("OAuthTwitter");
			super.addEventListener(OAuthEvent.ON_ACCESS_TOKEN_RECEIVED, this.onSccessTokenRecievedTwitter);
		}
		
		private function onSccessTokenRecievedTwitter(e:OAuthEvent):void{
			var qs:QueryString = new QueryString(e.data);
			if( qs.length ){
				this._screen_name = qs.getValue( "screen_name" );
				this._user_id = qs.getValue( "user_id" );
				trace("screen_name:" + this._screen_name);
				trace("user_id:" + this._user_id);
			}
		}
		
		// ------------------------------------------------------------------------------
		// statuses/update
		// http://apiwiki.twitter.com/Twitter-API-Documentation
		public function StatusesUpdate(status:String):void{
			var variables:URLVariables = new URLVariables();
			variables.status = status;
			var request:URLRequest = super.buildURLRequest(URLRequestMethod.POST, "http://twitter.com/statuses/update.xml", variables, true);
			
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, this.onStatusesUpdate, false, 0, true);
			loader.load(request);
		}
		
		private function onStatusesUpdate(e:Event):void{
			var loader:URLLoader = e.currentTarget as URLLoader;
			loader.removeEventListener(Event.COMPLETE, this.onStatusesUpdate);
			
			try{
				var response_xml:XML = new XML(loader.data);
			}catch(error:Error){
				this.dispatchEvent(new TwitterEvent(TwitterEvent.XML_PARCE_ERROR, loader.data));
			}
			
			var res_status:TwitterStatus = new TwitterStatus();
			if(this.use_parser){
				res_status.status_xml = response_xml;
			}
			
			this.dispatchEvent(new TwitterEvent(TwitterEvent.STATUS_UPDATE, loader.data, response_xml, res_status));
		}

		// ------------------------------------------------------------------------------
		// statuses/home_timeline
		public function StatusesHomeTimeline():void{
			var variables:URLVariables = new URLVariables();
			var request:URLRequest = super.buildURLRequest(URLRequestMethod.GET, "https://api.twitter.com/1/statuses/home_timeline.xml", variables, true);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, this.onStatusesHomeTimeline, false, 0, true);
			loader.load(request);
		}
		
		private function onStatusesHomeTimeline(e:Event):void{
			var loader:URLLoader = e.currentTarget as URLLoader;
			loader.removeEventListener(Event.COMPLETE, this.onStatusesHomeTimeline);

			var res_timeline:Array = new Array();
			try{
				var response_xml:XML = new XML(loader.data);
				var timeline:XMLList = response_xml.status;
				if(this.use_parser){
					for each( var status_xml:XML in timeline ) {
						var status:TwitterStatus = new TwitterStatus();
						status.status_xml = status_xml;
						res_timeline.push(status);
					}
				}
				this.dispatchEvent(new TwitterEvent(TwitterEvent.ON_HOME_TIMELINE,loader.data,response_xml,null,res_timeline));
				
			}catch(error:Error){
				this.dispatchEvent(new TwitterEvent(TwitterEvent.XML_PARCE_ERROR, loader.data));
			}
		}
		
		// ------------------------------------------------------------------------------
		// mentions
		public function statusesMentions():void{
			var variables:URLVariables = new URLVariables();
			var request:URLRequest = super.buildURLRequest(URLRequestMethod.GET, "http://api.twitter.com/1/statuses/mentions.xml", variables, true);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, this.onStatusesMentions, false, 0, true);
			loader.load(request);
		}
		public function onStatusesMentions(e:Event):void{
			var loader:URLLoader = e.currentTarget as URLLoader;
			loader.removeEventListener(Event.COMPLETE, this.onStatusesMentions);

			var res_timeline:Array = new Array();
			try{
				var response_xml:XML = new XML(loader.data);
				var timeline:XMLList = response_xml.status;
				if(this.use_parser){
					for each( var status_xml:XML in timeline ) {
						var status:TwitterStatus = new TwitterStatus();
						status.status_xml = status_xml;
						res_timeline.push(status);
					}
				}
				this.dispatchEvent(new TwitterEvent(TwitterEvent.ON_MENTIONS,loader.data,response_xml,null,res_timeline));
				
			}catch(error:Error){
				this.dispatchEvent(new TwitterEvent(TwitterEvent.XML_PARCE_ERROR, loader.data));
			}
		}
		
		// search
		public function search(word:String = null, exact_word:String = null, from:String = null):void{
			var q:Array = new Array();
			if(word){
				q.push(word);
			}
			if(exact_word){
				q.push('"' + exact_word + '"');
			}
			if(from){
				q.push("from:" + from);
			}
			
			var variables:URLVariables = new URLVariables();
			variables.q = q.join(" ");
			var request:URLRequest = new URLRequest("http://search.twitter.com/search.json");
			request.method = URLRequestMethod.GET;
			request.data = variables;
			//super.buildURLRequest(URLRequestMethod.GET, "http://search.twitter.com/search.xml", variables, true);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, this.onSearch, false, 0, true);
			loader.load(request);
		}
		
		private function onSearch(e:Event):void{
			var loader:URLLoader = e.currentTarget as URLLoader;
			loader.removeEventListener(Event.COMPLETE, this.onSearch);
			
			var res_timeline:Array = new Array();
			try{
				var resJsonObj:Object = JSON.decode(loader.data);
				var timeline:Array = resJsonObj.results;
				if(this.use_parser){
					for each( var status:Object in timeline ) {
						var ts:TwitterStatus = new TwitterStatus();
						ts.status_json = status;
						res_timeline.push(ts);
					}
				}
				this.dispatchEvent(new TwitterEvent(TwitterEvent.ON_MENTIONS,loader.data,null,null,res_timeline));
				
			}catch(error:Error){
				this.dispatchEvent(new TwitterEvent(TwitterEvent.XML_PARCE_ERROR, loader.data));
			}

		}
		
		public function VerifyCredentials():void{
			var request:URLRequest = super.buildURLRequest(URLRequestMethod.GET, "https://api.twitter.com/1/account/verify_credentials.xml", new URLVariables(), true);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, this.onVerifyCredentials, false, 0, true);
			loader.load(request);
		}
		
		private function onVerifyCredentials(e:Event):void{
			var loader:URLLoader = e.currentTarget as URLLoader;
			loader.removeEventListener(Event.COMPLETE, this.onVerifyCredentials);
			trace("onVerifyCredentials:\n"+loader.data);
		}

	}
}